package com.jjw.route.service.impl;

import com.jjw.route.config.LoginUserInterceptor;
import com.jjw.route.dao.UserDao;
import com.jjw.route.entity.UserEntity;
import com.jjw.route.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jjw.route.utils.PageUtils;
import com.jjw.route.utils.Query;

import com.jjw.route.dao.AttentionDao;
import com.jjw.route.entity.AttentionEntity;
import com.jjw.route.service.AttentionService;


@Service("attentionService")
public class AttentionServiceImpl extends ServiceImpl<AttentionDao, AttentionEntity> implements AttentionService {
    @Autowired
    AttentionDao attentionDao;
    @Autowired
    UserDao userDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttentionEntity> page = this.page(
                new Query<AttentionEntity>().getPage(params),
                new QueryWrapper<AttentionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R addAttentionRelation(String name) {
        UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("name", name));
        AttentionEntity attentionEntities = attentionDao.selectOne(new QueryWrapper<AttentionEntity>()
                .eq("luid", LoginUserInterceptor.loginUser.get()).eq("ruid", userEntity.getId()));
        if (attentionEntities == null) {
            AttentionEntity attentionEntity = new AttentionEntity();
            attentionEntity.setLuid(LoginUserInterceptor.loginUser.get());
            attentionEntity.setRuid(userEntity.getId());
            attentionDao.insert(attentionEntity);
            return R.ok();
        }
        return R.error("你已经关注过了");
    }

    @Override
    public boolean attentionSearch(String name){
        UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("name", name));
        AttentionEntity attentionEntities = attentionDao.selectOne(new QueryWrapper<AttentionEntity>()
                .eq("luid", LoginUserInterceptor.loginUser.get()).eq("ruid", userEntity.getId()));
        if (attentionEntities != null) return true;
        else return false;
    }


    @Override
    public List<Integer> getAttention(int uid) {
        List<AttentionEntity> attentionEntities = attentionDao.selectList(new QueryWrapper<AttentionEntity>().eq("luid", uid));
        List<Integer> ruids = new ArrayList<>();
        for (AttentionEntity attentionEntity : attentionEntities) {
            ruids.add(attentionEntity.getRuid());
        }
        return ruids;
    }
}